package com.catchman.quartz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.catchman.entity.SysJob;
import com.catchman.service.SysJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 项目启动注入已启动的定时任务
 * @author CatchMan
 * @date 2019-05-21
 */
@Component
public class JobInitRunner implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(JobInitRunner.class);
    @Autowired
    private QuartzManager quartzManager;
    @Autowired
    private SysJobService sysJobService;

    /**
     * 项目重启后，初始化原本已经运行的定时任务
     * 或者采用注释：被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行，并且只会被服务器调用一次，类似于Servlet的inti()方法
     *
     * @param applicationArguments
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments applicationArguments){
        System.out.println("--------------------注入定时任务---------------------");
        List<SysJob> sysJobs = sysJobService.list(new QueryWrapper<SysJob>().eq("status", true));
        sysJobs.forEach(sj -> {
            try {
                quartzManager.addJob(sj.getJobName(), sj.getGroupName(), sj.getClazzPath(), sj.getCron());
            } catch (Exception e) {
                logger.error("初始化启动定时任务失败！" + e.getLocalizedMessage());
                e.printStackTrace();
            }
        });
        System.out.println("--------------------定时任务注入完成---------------------");
    }
}
